package cn.ejopenai.demo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class ChatGPTUtil2 {
    // 设置 API 密钥
    private static String url= "https://api.openai.com/v1/chat/completions";
    private static String apiKey = "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";

    public static void main(String[] args) throws Exception {
        // 1 设置 OpenAI API 的访问参数
        // {"model": "gpt-3.5-turbo","messages": [{ "role": "user", "content": "who are you" },{ "role": "assistant", "content": "", "session_id": "willie123" }]}
        JSONObject requestMessage = new JSONObject();
        requestMessage.put("model","gpt-3.5-turbo");
        // 消息数组
        JSONArray messageArr = new JSONArray();
        // 消息对象
        JSONObject messageObj = new JSONObject();
        messageObj.put("role","system");
        messageObj.put("content","你是叩丁狼AI客服小丽，叩丁狼是一家IT教育培训机构，宗旨是让更多想从事IT行业的青年职业道路走的坚实而长远");

        messageArr.add(messageObj);
        requestMessage.put("messages",messageArr);

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()){
            String line = sc.nextLine();
            // 会话记录
            JSONObject messageObj2 = new JSONObject();
            messageObj2.put("role","user");
            messageObj2.put("content",line);
            messageArr.add(messageObj2);

            // 响应加入
            String resultMsg = sendRequest(requestMessage.toJSONString());
            JSONObject messageObj3 = new JSONObject();
            messageObj3.put("role","assistant");
            messageObj3.put("content",resultMsg);
            messageArr.add(messageObj3);
            System.out.println(requestMessage.toJSONString());
        }
    }

    public static String sendRequest(String content){
        try{
            // 创建 HTTP 的 post 请求
            URL obj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)obj.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","Bearer " + apiKey);
            conn.setRequestProperty("Content-Type","application/json");

            //String body = "{\"model\":\"gpt-3.5-turbo\",\"messages\":[{ \"role\": \"user\", \"content\":\"你是谁？\" }]}";
            String body = content;
            System.out.println(body);
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(body);
            writer.flush();

            // 获取响应
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String outLine;
            StringBuffer response = new StringBuffer();
            while((outLine = br.readLine()) != null){
                response.append(outLine);
            }

            // 结果数据处理 "content":
            System.out.println("allMessage:" + response.toString());
            return response.toString().split("\"content\": \"")[1].split("\"")[0];
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
